// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const $ = db.command.aggregate

// 创建集合云函数入口函数
exports.main = async (event, context) => {
    try {
        let {
            conditions
        } = event.data

        // 获取当前日期
        const now = new Date();
        const startOfDay = new Date(now);
        startOfDay.setHours(0, 0, 0, 0);
        const endOfDay = new Date(now);
        endOfDay.setHours(23, 59, 59, 999);

        let query = db.collection('orderList')

        // 查询今日销售数据
        const salesResult = await query.aggregate().match({
                _openid: conditions._openid,
                orderStatus: {
                    $not: {
                        $in: [1, 5], // 查询状态除了待付款和售后以为的订单
                    }
                },
                createTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                },
                payTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                }
            })
            .group({
                _id: null, // 不分组，用于计算总和
                todaySales: $.sum("$orderTotalPrice"), // 今日销售
                memberSales: $.sum({ // 会员消费
                    $cond: {
                        if: {
                            $eq: ['$userInfo.level', 1]
                        },
                        then: '$orderTotalPrice',
                        else: 0
                    }
                }),
                crossBorderMemberSales: $.sum({ // 跨界会员消费
                    $cond: {
                        if: {
                            $eq: ['$userInfo.level', 2]
                        },
                        then: '$orderTotalPrice',
                        else: 0
                    }
                }),
            })
            .end()

        // 查询今日销冠商品
        const topProductResult = await query.aggregate().match({
                _openid: conditions._openid,
                orderStatus: {
                    $not: {
                        $in: [1, 5], // 查询状态除了待付款和售后以为的订单
                    }
                },
                createTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                },
                payTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                }
            })
            .unwind('$goodsName') // 展开商品名
            .group({
                _id: '$goodsName', // 按商品名分组
                totalQuantity: $.sum('$buyNum'), // 购买总数
                totalAmount: $.sum('$orderTotalPrice'), // 购买总金额
                goodsName: $.first('$goodsName'), // 商品名
            })
            .sort({
                totalQuantity: -1
            }) // 按销量降序排序
            .limit(1) // 只取销量最高的商品
            .end()

        if (salesResult.list.length > 0 && topProductResult.list.length > 0) {
            return {
                code: 200,
                msg: "操作成功",
                data: {
                    todaySales: salesResult.list[0].todaySales,
                    memberSales: salesResult.list[0].memberSales,
                    crossBorderMemberSales: salesResult.list[0].crossBorderMemberSales,
                    totalQuantity: topProductResult.list[0].totalQuantity,
                    totalAmount: topProductResult.list[0].totalAmount,
                    goodsName: topProductResult.list[0].goodsName,
                },
            }
        } else {
            return {
                code: 200,
                msg: "操作成功",
                data: {
                    todaySales: 0,
                    memberSales: 0,
                    crossBorderMemberSales: 0,
                    totalQuantity: 0,
                    totalAmount: 0,
                    goodsName: "今日暂无订单",
                },
            }
        }
    } catch (err) {
        return {
            code: 500,
            message: err.message
        }
    }
}